package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetMealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.List;

/**
 * @program: itcast_health
 * @create: 2019-10-24 15:33
 * @author: li he
 * @description:
 */
@RestController
@RequestMapping("setMeal")
public class SetMealController {
    @Reference
    private SetMealService sertMealService;

    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("getSetMeal")
    public Result getSetMeal() {
        try {


            String list = jedisPool.getResource().get(RedisConst.SETMEAL_LIST_DB_DATA);

            List<Setmeal> setmealList = null;
            if (list != null && list.length() > 0) {  //如果有缓存就用缓存的
                //使用redis缓存数据库中的数据
                System.out.println("使用redis缓存数据库中的数据");
                setmealList = JSONObject.parseArray(list, Setmeal.class);
            } else { //如果没有缓存就查数据库
                System.out.println("从MySql数据库中查询");
                setmealList = sertMealService.findAll();
                list = JSONObject.toJSONString(setmealList);
                jedisPool.getResource().set(RedisConst.SETMEAL_LIST_DB_DATA, list);
            }


            return new Result(true, MessageConst.QUERY_SETMEAL_SUCCESS, setmealList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConst.QUERY_SETMEAL_FAIL);
        }
    }

    @RequestMapping("findSetMealDetailsById")
    public Result findSetMealDetailsById(Integer id) {
        try {
            Setmeal setMeal = sertMealService.findSetMealDetailsById(id);
            return new Result(true, MessageConst.QUERY_SETMEAL_SUCCESS, setMeal);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.QUERY_SETMEAL_FAIL);
        }
    }
    @RequestMapping("findById")
    public Result findById(Integer id){
        try {
            Setmeal setMeal = sertMealService.findById(id);
            return new Result(true, MessageConst.QUERY_SETMEAL_SUCCESS, setMeal);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.QUERY_SETMEAL_FAIL);
        }
    }

}